package com.mjf.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mjf.system.domain.MjfSerialNumber;
import com.mjf.system.mapper.MjfSerialNumberMapper;
import com.mjf.system.service.IMjfSerialNumberService;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 序列号 服务实现类
 * </p>
 *
 * @author
 * @since 2024-11-27
 */
@Service
public class MjfSerialNumberServiceImpl extends ServiceImpl<MjfSerialNumberMapper, MjfSerialNumber> implements IMjfSerialNumberService {

	@Override
    synchronized public String getNextCgPositionNumber(String type) {
        List<MjfSerialNumber> list = list(Wrappers.<MjfSerialNumber>lambdaQuery()
            .eq(MjfSerialNumber::getType, type));
        if (CollectionUtils.isNotEmpty(list)) {
            MjfSerialNumber MjfSerialNumber = list.get(0);
            if (!MjfSerialNumber.getNumberDate().isEqual(LocalDate.now())) {
                MjfSerialNumber.setNumberDate(LocalDate.now());
                MjfSerialNumber.setNowNum(0);
            }
            MjfSerialNumber.setNowNum(MjfSerialNumber.getNowNum() + 1);
            updateById(MjfSerialNumber);
            return fexNumber(type, MjfSerialNumber.getNowNum());
        } else {
            MjfSerialNumber MjfSerialNumber = new MjfSerialNumber();
            MjfSerialNumber.setNumberDate(LocalDate.now());
            MjfSerialNumber.setType(type);
            MjfSerialNumber.setNowNum(1);
            save(MjfSerialNumber);
            return fexNumber(type, MjfSerialNumber.getNowNum());
        }
    }


    public String fexNumber(String type, Integer serialNumber) {
        // 获取当前日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = dateFormat.format(new Date());
        // 格式化流水号，保证6位，不足6位用0补齐
        String serialStr = String.format("%06d", serialNumber);
        // 拼接结果
        return type + dateStr + serialStr;
    }
}
